<?php


namespace app\admin\controller;


use app\common\model\GoodsModel;
use app\common\model\StorageLogModel;
use app\common\model\StorageManageModel;
use app\common\model\StorageModel;
use cmf\controller\AdminBaseController;
use GuzzleHttp\Client;
use think\db\Query;

class ManageController extends AdminBaseController
{
    public function index()
    {
        $param = $this->request->param();
        $list = StorageManageModel::where(function (Query $query) use ($param) {
            $query->where('is_del', 0);

            if (!empty($param['keyword'])) {
                $query->where('name', 'like', "%{$param['keyword']}%");
            }
        })->order('id desc')->paginate()
            ->each(function ($v, $k) {

            });
        $this->assign('list', $list);
        return $this->fetch();
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (StorageManageModel::create($param)) {
                $this->success('添加成功');
            } else {
                $this->error('添加失败');
            }
        }
        return $this->fetch();
    }

    public function edit($id)
    {
        $data = StorageManageModel::where('id', $id)->find();
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if ($data->save($param)) {
                $this->success('编辑成功');
            } else {
                $this->error('编辑失败');
            }
        }
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function del($id)
    {
        if (StorageManageModel::update(['is_del' => 1, 'id' => $id])) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    public function sync_storage($id)
    {
        $manage = StorageManageModel::where('id', $id)->find();
        if (!$manage || $manage['is_del'] == 1) {
            $this->error('快递公司不存在');
        }

        if ($id == 1) {
            $client = new Client();
            try {
                $resp = $client->request('post', 'https://www.lipindao.com/api/goods/storelist', [
                    'headers' => ['token' => $manage['token']]
                ]);
                $contents = ($resp->getBody()->getContents());
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }

            $data = json_decode($contents, true);
            if ($data['code'] == 1) {
                $list = $data['data']['storelist'];
                if (!$list) {
                    $this->error('没有仓库数据');
                }

                foreach ($list as $item) {
                    $item['sid'] = $item['id'];
                    $item['mid'] = $id;
                    unset($item['id']);
                    $storage = StorageModel::where(['mid' => $id, 'sid' => $item['sid']])->find();
                    if ($storage) {
                        $storage->save($item, ['id' => $storage['id']]);
                    } else {
                        StorageModel::create($item);
                    }
                }
                $this->success('success');
            } else {
                $this->error('获取仓库数据异常');
            }
        } else {
            $this->error('暂无合作');
        }

    }

    public function sync_goods($id)
    {
        $manage = StorageManageModel::where('id', $id)->find();
        if (!$manage || $manage['is_del'] == 1) {
            $this->error('快递公司不存在');
        }

        if ($id == 1) {
            if ($this->request->isPost()) {
                $list = cache('sync_goods_' . $id);
                if (!$list) {
                    $this->error('请刷新页面后重试');
                }

                $store = StorageModel::where(['mid' => $id, 'is_del' => 0])->find();
                if (!$store) {
                    $this->error('请先同步' . $manage['name'] . '仓库数据');
                }

                $ids = $this->request->param('ids', []);
                if (empty($ids)) {
                    GoodsModel::update(['isdel' => 1], ['mid' => $id]);
                    $this->success('ok');
                }

                //反选商品直接删除
                GoodsModel::where(['mid' => $id, 'isdel' => 1])->where('sid', 'not in', $ids)->update(['isdel' => 1]);

                //处理选择商品
                foreach ($list as $item) {
                    foreach ($ids as $sid) {
                        if ($item['id'] == $sid) {
                            //组装数据
                            $data = [
                                'goods_images' => json_encode([$item['goods_image']], true),
                                'goods_price'  => $item['apiprice'],
                                'goods_name'   => $item['name'],
                                'image'        => $item['goods_image'],
                                'weight'       => $item['weight'],
                                'mid'          => $id,
                                'sid'          => $sid,
                                'goods_num'    => 1,
                                'isdel'        => 0,
                            ];

                            $goods = GoodsModel::where(['mid' => $id, 'sid' => $sid])->find();
                            if ($goods) {
                                $goods->save($data);
                            } else {
                                $goods = GoodsModel::create($data);
                            }

                            $store_list = explode(',', $item['store_name']);
                            foreach ($store_list as $store_name) {
                                $store = StorageModel::where(['mid' => $id, 'store_name' => $store_name])->find();
                                if ($store) {
                                    $bool = StorageLogModel::where(['sid' => $store['id'], 'goods_id' => $goods['id']])->find();
                                    if (!$bool) {
                                        StorageLogModel::create(['sid' => $store['id'], 'goods_id' => $goods['id'], 'storage_name' => $store_name, 'freight_price' => $store['price'], 'goods_num' => 1]);
                                    } else {
                                        $bool->save(['storage_name' => $store_name, 'freight_price' => $store['price'], 'goods_num' => 1]);
                                    }
                                }
                            }
                        }
                    }

                }
                $this->success('ok');
            }

            $client = new Client();
            try {
                $resp = $client->request('post', 'https://www.lipindao.com/api/goods/goodslist', [
                    'headers' => ['token' => $manage['token']]
                ]);
                $contents = ($resp->getBody()->getContents());
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }

            $data = json_decode($contents, true);
            if ($data['code'] == 1) {
                $list = $data['data']['goodslist'];
                if (!$list) {
                    $this->error('没有商品数据');
                }

                foreach ($list as &$item) {
                    $item['sync_ever'] = 0;
                    if (GoodsModel::where(['mid' => $id, 'sid' => $item['id'], 'isdel' => 0])->find()) {
                        $item['sync_ever'] = 1;
                    }
                }
                cache('sync_goods_' . $id, $list, ['expire' => strtotime('+2 hour')]);
                $this->assign('list', $list);
                $this->assign('id', $id);
                return $this->fetch();
            } else {
                $this->error('获取仓库数据异常');
            }
        } else {
            $this->error('暂无合作');
        }

    }


}